const axios = require('axios')

// cookies 跨域
axios.defaults.withCredentials = true

// create an axios instance
const service = axios.create({
  // baseURL: process.env.BASE_API, // url = base url + request url
  withCredentials: true, // send cookies when cross-domain requests
  timeout: 10000, // request timeout
})

service.CancelToken = axios.CancelToken

// 请求拦截器
service.interceptors.request.use(
  config => {
    config.headers['Content-Type'] = 'application/json';
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => response.data,
  error => {

    if (axios.isCancel(error)) {
      // 手动取消的接口, 无需关心
      return Promise.reject(new Error('request_isCancel'))
    }

    let status = 0
    try {
      status = error.response.status;
    } catch (e) {
      if (error.toString().indexOf('Error: timeout') !== -1) {
        return Promise.reject(error)
      }
      if (error.toString().indexOf('Error: Network Error') !== -1) {
        return Promise.reject(error)
      }
    }
    return Promise.reject(error.response);
  }
)

module.exports = service
